<template>
  <el-dialog
    v-model="dialogVisible"
    :destroy-on-close="true"
    :align-center="true"
    width="50%"
    :title="`${dialogData.title}招工信息`"
  >
    <el-form
      ref="jobFormRef"
      :rules="rules"
      :disabled="dialogData.isView"
      :model="dialogData.itemInfo"
      label-width="180px"
      label-suffix=" :"
    >
      <div class="info-title">基本信息</div>
      <el-form-item label="职位类别">
        <el-tree-select
          filterable
          v-model="dialogData.itemInfo.jobTypeId"
          :data="dialogData.jobTypes"
          :render-after-expand="false"
          placeholder="请选择职位类别"
          style="width: 100%"
        ></el-tree-select>
      </el-form-item>
      <el-form-item label="职位名称" prop="title">
        <el-input size="large" placeholder="请输入职位名称" v-model="dialogData.itemInfo.title" maxlength="12" show-word-limit />
      </el-form-item>
      <el-form-item label="招聘数量">
        <el-input-number
          size="large"
          style="width: 100%; text-align: left"
          placeholder="请输入招聘人数"
          v-model="dialogData.itemInfo.needCnt"
        />
      </el-form-item>
      <el-form-item label="薪资类型">
        <el-input v-model="dialogData.itemInfo.priceStart" placeholder="Please input" class="input-with-select">
          <template #append>
            <el-select v-model="dialogData.itemInfo.priceType" placeholder="Select" style="width: 80px">
              <el-option v-for="item in priceTypeEnum" :label="item.label" :value="item.value" :key="item.value" />
            </el-select>
          </template>
        </el-input>
      </el-form-item>
      <el-form-item label="工作地址">
        <div class="address-wrapper">
          <div class="address-input">
            <el-input
              readonly
              placeholder="请选择详细地址"
              v-model="dialogData.itemInfo.jobAddress.address"
              size="large"
              maxlength="80"
              show-word-limit
            >
            </el-input>
          </div>
          <div class="address-btn">
            <el-button :icon="Location" size="large" type="primary" style="width: 100%" @click="handleOpenDialog">
              请选择地址
            </el-button>
          </div>
        </div>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" :icon="Plus">保存为常用地址</el-button><el-button :icon="Search">从常用地址中选择</el-button>
      </el-form-item>
      <el-form-item label="结算周期">
        <el-radio-group v-model="dialogData.itemInfo.settleType">
          <el-radio v-for="item in settlementEnum" :label="item.value" :key="item.value">
            {{ item.label }}
          </el-radio>
        </el-radio-group>
      </el-form-item>
      <el-form-item label="年龄要求">
        <el-row :gutter="20">
          <el-col :span="10">
            <el-input-number
              size="large"
              style="width: 100%; text-align: left"
              placeholder="请输入招聘人数"
              v-model="dialogData.itemInfo.sage"
              :min="11"
            />
          </el-col>
          <el-col :span="2" align="center">至</el-col>
          <el-col :span="11">
            <el-input-number
              size="large"
              style="width: 100%; text-align: left"
              placeholder="请输入招聘人数"
              v-model="dialogData.itemInfo.eage"
              :min="16"
              :max="100"
            />
          </el-col>
        </el-row>
      </el-form-item>
      <el-form-item label="性别要求">
        <el-select
          style="width: 100%"
          v-model="dialogData.itemInfo.requireSex"
          class="m-2"
          placeholder="请选择工作年限要求"
          size="large"
        >
          <el-option v-for="item in genderType" :label="item.label" :value="item.value" :key="item.value" />
        </el-select>
      </el-form-item>

      <el-form-item label="学历要求">
        <el-select
          style="width: 100%"
          v-model="dialogData.itemInfo.requireEdu"
          class="m-2"
          placeholder="请选择工作年限要求"
          size="large"
        >
          <el-option v-for="item in degrees" :label="item.label" :value="item.value" :key="item.value" />
        </el-select>
      </el-form-item>
      <div class="info-title">工作信息</div>
      <el-form-item label="工作日期">
        <el-radio-group v-model="dialogData.itemInfo.termType">
          <el-radio v-for="item in jobRequirementEnum" :label="item.value" :key="item.value">
            {{ item.label }}
          </el-radio>
        </el-radio-group>
      </el-form-item>
      <el-form-item label="工作时段">
        <div class="work-wrapper">
          <div class="item-wrapper" v-for="(item, index) in dialogData.worktimes" :key="index">
            <el-time-select v-model="item.stime" start="00:00" step="00:15" end="24:00" placeholder="Select time" />
            <el-time-select
              class="item-mid"
              v-model="item.etime"
              start="00:00"
              step="00:15"
              end="24:00"
              placeholder="Select time"
            />
            <el-button type="danger" :icon="Delete" size="small" circle @click="handleRemoveWorkTime(index)" />
          </div>
          <div class="btn-wrapper">
            <el-button type="primary" :icon="Plus" @click="handleAddWorkTime">添加工作时段</el-button>
          </div>
        </div>
      </el-form-item>
      <el-form-item label="工作内容" prop="content">
        <WangEditor height="200px" v-model:value="dialogData.itemInfo.content" />
      </el-form-item>
      <el-form-item label="工作标签">
        <el-select
          size="large"
          style="width: 100%"
          v-model="dialogData.itemInfo.tags"
          multiple
          multiple-limit="5"
          placeholder="请选择福利"
        >
          <el-option v-for="item in options" :key="item.id" :label="item.name" :value="item.id" />
        </el-select>
      </el-form-item>
      <el-form-item label="其它福利">
        <div class="custom-wrapper">
          <el-tag
            v-for="tag in dynamicTags"
            :key="tag"
            class="mx-1"
            closable
            :disable-transitions="false"
            @close="handleClose(tag)"
          >
            {{ tag }}
          </el-tag>
          <el-input
            v-if="inputVisible"
            placeholder="请填写"
            ref="InputRef"
            v-model="inputValue"
            class="mx-1 w-20"
            size="small"
            maxlength="4"
            show-word-limit
            @keyup.enter="handleInputConfirm"
            @blur="handleInputConfirm"
          />
          <el-button v-else class="mx-1" size="small" @click="showInput"> + 自定义福利 </el-button>
        </div>
      </el-form-item>
      <div class="info-title">联系方式</div>
      <el-form-item label="联系人">
        <el-input
          placeholder="请填写联系人"
          v-model="dialogData.itemInfo.contactor"
          size="large"
          maxlength="15"
          show-word-limit
        />
      </el-form-item>
      <el-form-item label="联系电话">
        <el-input
          placeholder="请填写联系人电话"
          v-model="dialogData.itemInfo.contactPhone"
          size="large"
          maxlength="15"
          show-word-limit
        />
      </el-form-item>
    </el-form>
    <template #footer>
      <el-button v-show="!dialogData.isView" @click="handleJobOffline">下架</el-button>
      <el-input
        v-model="refuseContent"
        v-show="dialogData.isView"
        placeholder="请填写拒绝原因"
        :prefix-icon="EditPen"
        style="width: 260px; margin-left: 10px"
      />
      <el-button size="large" type="danger" @click="handleAduitFail" v-show="dialogData.isView">拒绝</el-button>
      <el-button size="large" type="success" @click="handleAduitPass" v-show="dialogData.isView">通过</el-button>
      <el-button size="large" type="primary" @click="handleLoadNext" v-show="dialogData.isView">审核下一个</el-button>
      <el-button @click="dialogVisible = false">关闭</el-button>
      <el-button type="primary" size="large" v-show="!dialogData.isView" @click="handleSubmit" :loading="btnLoading">
        确认发布
      </el-button>
      <el-divider />
      <div class="jobstatus-wrapper" v-show="dialogData.isView">
        <el-alert
          :title="`岗位状态 &nbsp;:&nbsp; ${filterEnum(dialogData.itemInfo.status, jobStatusType)}`"
          type="info"
          show-icon
          :closable="false"
        />
      </div>
    </template>
  </el-dialog>
  <mapDialog ref="dialogRef" @refresh-data="handleRefreshMapData"></mapDialog>
</template>
<script lang="ts" setup>
import { getOddJobTypesTreeApi } from "@/api/modules/sysjob/tp";
import { getOptTitle, OptEnum } from "@/biz/eenum/appEnum";
import { CommonTree } from "@/biz/interface";
import { DialogParam } from "@/biz/interface/DialogType";
import { OddJobEntity } from "@/biz/interface/JobType";
import { ElInput, ElMessage, FormInstance } from "element-plus";
import { nextTick, onMounted, reactive, ref } from "vue";
import { jobRequirementEnum, settlementEnum, priceTypeEnum } from "@/biz/datas/jobData";
import { genderType } from "@/biz/datas/sysData";
import { degrees } from "@/biz/datas/formDrops";
import { getJobTagsByTypeVoListApi } from "@/api/modules/sysjob/jobtag";
// import { useAddress } from "@/biz/hooks/useAddress";
import { saveJobApi, getJobInfoApi, setJobOffline, getNextJobApi } from "@/api/modules/cpyjob/oddjob";
import mapDialog, { AddressVo } from "@/components/Map/index.vue";
import { Location, Delete, Plus, Search, EditPen } from "@element-plus/icons-vue";
import WangEditor from "@/components/WangEditor/index.vue";
import { useHandleData } from "@/hooks/useHandleData";
import { auditFailApi, auditPassApi } from "@/api/modules/sysjob/job";
import { jobStatusType } from "@/biz/datas/jobData";
import { filterEnum } from "@/utils";

interface WorkTime {
  stime: string;
  etime: string;
}

interface PostDialogOption extends DialogParam {
  //弹出表单的标题
  title: string;
  // 是否是查看状态，查看状态是不可以提交数据
  isView: boolean;
  // 图片
  worktimes: WorkTime[];
  // 岗位类型树
  jobTypes: CommonTree[];
  //当前的数据对象
  itemInfo: OddJobEntity;
}

//提交按钮，避免多次提交
const btnLoading = ref(false);
const options = ref([] as any);
//弹出框的参数
const dialogVisible = ref(false);
const dialogData = reactive<PostDialogOption>({
  optType: OptEnum.UNKNOW,
  title: "",
  isView: false,
  worktimes: [{ stime: "8:00", etime: "12:00" }],
  jobTypes: [],
  itemInfo: {
    // * 标题
    title: "",
    // * 类型
    jobTypeId: undefined,
    // * 招聘人数
    needCnt: 0,
    // * 价格开始
    priceStart: "20",
    priceType: 1,
    // * 职位描述
    content: "",
    // * 联系人
    contactor: "",
    // * 联系电话
    contactPhone: "",
    // 地址信息
    jobAddress: {},
    // *  职位福利
    tags: [],
    // 时间段
    timePeriods: [],
    // *  薪资结算
    settleType: 1,
    // 薪资说明
    termType: 1,
    sage: 16
  }
});

//数据较验
const rules = reactive({
  title: [{ required: true, message: "请填写职位名称", trigger: "blur" }],
  content: [{ required: true, message: "请填写岗位内容", trigger: "blur" }]
});

//页面事件
const emits = defineEmits(["refresh-list"]);

// 提交数据（新增/编辑）
const jobFormRef = ref<FormInstance>();
const handleSubmit = () => {
  btnLoading.value = true;
  jobFormRef.value!.validate(async valid => {
    if (!valid) {
      btnLoading.value = false;
      return;
    }
    try {
      if (dialogData.optType === OptEnum.CREATE || dialogData.optType === OptEnum.EDIT) {
        if (!dialogData.itemInfo.jobAddress.areaName) {
          ElMessage.error("请选择区域信息");
          return;
        }

        //拼成后台的坐标格式
        dialogData.itemInfo.jobAddress.location = dialogData.itemInfo.jobAddress.lng + "," + dialogData.itemInfo.jobAddress.lat;

        // 时间段
        dialogData.itemInfo.timePeriods = dialogData.worktimes;

        // 填充自定义标签
        dialogData.itemInfo.customTags = "";
        if (dynamicTags.value && dynamicTags.value.length > 0) {
          dialogData.itemInfo.customTags = dynamicTags.value.join(",");
        }

        // console.log("提交的数据", dialogData.itemInfo);

        let res = await saveJobApi({
          ...dialogData.itemInfo
        });
        if (res.data) {
          ElMessage.success({ message: `保存成功！` });
          //刷新列表数据
          // eslint-disable-next-line vue/custom-event-name-casing
          emits("refresh-list");
          dialogVisible.value = false;
        }
      }
    } catch (error) {
      console.log("出现异常情况,", error);
    } finally {
      btnLoading.value = false;
    }
  });
};

// 岗位下架
const handleJobOffline = async () => {
  if (dialogData.rowData && dialogData.rowData.id) {
    let res = await setJobOffline({ id: dialogData.rowData.id });
    if (res.data) {
      ElMessage.success({ message: `岗位已下架` });
      //刷新列表数据
      // eslint-disable-next-line vue/custom-event-name-casing
      emits("refresh-list");
      dialogVisible.value = false;
    }
  }
};

// 添加一个时间段
const handleAddWorkTime = () => {
  dialogData.worktimes.push({ stime: "", etime: "" });
};

//移除一个时间段
const handleRemoveWorkTime = (idx: number) => {
  dialogData.worktimes.splice(idx, 1);
};

// 接收父组件传过来的参数
const acceptParams = (params: DialogParam): void => {
  dialogData.optType = params.optType;
  dialogData.rowData = params.rowData;
  dialogData.isView = dialogData.optType === OptEnum.VIEW;
  dialogData.title = getOptTitle(dialogData.optType);

  if (dialogData.optType === OptEnum.CREATE) {
    initItemInfo();
  } else if (dialogData.rowData && dialogData.rowData.id) {
    getItemInfo(dialogData.rowData.id);
  }

  dialogVisible.value = true;
};

//初始化页面的数据
const initItemInfo = (): void => {
  dialogData.itemInfo = {
    // * 标题
    title: "",
    // * 类型
    jobTypeId: undefined,
    // * 招聘人数
    needCnt: 0,
    // * 价格开始
    priceStart: "20",
    priceType: 1,
    // * 职位描述
    content: "",
    // * 联系人
    contactor: "",
    // * 联系电话
    contactPhone: "",

    jobAddress: {},
    // *  职位福利
    tags: [],
    timePeriods: [],
    // *  薪资结算
    settleType: 1,
    // 薪资说明
    termType: 1,
    sage: 16
  };
  dialogData.worktimes = [{ stime: "8:00", etime: "12:00" }];
};

//获取当前数据的详情，直接调用接口获取数据
const getItemInfo = async (id: string) => {
  if (id) {
    let { data } = await getJobInfoApi({ id });
    if (data) {
      dialogData.itemInfo = data as unknown as OddJobEntity;
      dialogData.worktimes = dialogData.itemInfo.timePeriods;
      dialogData.itemInfo.jobAddress = dialogData.itemInfo.jobAddress || {
        address: ""
      };
      if (dialogData.itemInfo.customTags) {
        dynamicTags.value = dialogData.itemInfo.customTags.split(",");
      } else {
        dynamicTags.value = [];
      }
    }
  }
};

//刷新地图的返回数据
const handleRefreshMapData = (val: AddressVo) => {
  // console.log("返回的地址信息", val);
  //填充地图数据
  dialogData.itemInfo.jobAddress = val;
};

// 打开 dialog(新增、查看、编辑)
const dialogRef = ref();
const handleOpenDialog = () => {
  let params = {};
  dialogRef.value.acceptParams(params);
};

const refuseContent = ref("");
const handleAduitFail = async () => {
  if (dialogData.itemInfo && dialogData.itemInfo.id) {
    await useHandleData(
      auditFailApi,
      { id: dialogData.itemInfo.id!, refuseCtn: refuseContent.value || "" },
      `【${dialogData.itemInfo.title}】岗位，审核不通过`
    );
  }
};

// 审核通过
const handleAduitPass = async () => {
  if (dialogData.itemInfo && dialogData.itemInfo.id) {
    await auditPassApi({
      id: dialogData.itemInfo.id
    }).then(res => {
      if (res.data) {
        ElMessage.success("审核通过");
      }
    });
  }
};

// 加载下一个
const handleLoadNext = () => {
  // getNextJobApi;
  if (dialogData.itemInfo && dialogData.itemInfo.id) {
    getNextItemInfo(dialogData.itemInfo.id);
  }
};

// 获取下一条等待审核的岗位信息
const getNextItemInfo = async (id: string) => {
  if (id) {
    let { data } = await getNextJobApi({ id });
    if (data) {
      dialogData.itemInfo = data as unknown as OddJobEntity;
      dialogData.worktimes = dialogData.itemInfo.timePeriods;
      dialogData.itemInfo.jobAddress = dialogData.itemInfo.jobAddress || {
        address: ""
      };
    } else {
      ElMessage.success("没有待审核数据了.");
    }
  }
};

const inputValue = ref("");
const dynamicTags = ref([]);
const inputVisible = ref(false);
const InputRef = ref<InstanceType<typeof ElInput>>();

const handleClose = (tag: string) => {
  dynamicTags.value.splice(dynamicTags.value.indexOf(tag), 1);
};

const showInput = () => {
  inputVisible.value = true;
  nextTick(() => {
    InputRef.value!.input!.focus();
  });
};

const handleInputConfirm = () => {
  if (inputValue.value) {
    if (dynamicTags.value && dynamicTags.value.length > 2) {
      ElMessage.error({ message: `最多可添加3个自定义福利.` });
      return;
    }
    dynamicTags.value.push(inputValue.value);
  }
  inputVisible.value = false;
  inputValue.value = "";
};

onMounted(() => {
  getOddJobTypesTreeApi({}).then(res => {
    dialogData.jobTypes = res.data as unknown as CommonTree[];
  });
  getJobTagsByTypeVoListApi({ type: 3, pageSize: 50 }).then(res => {
    options.value = res.data?.list;
  });
});

//页面参数
defineExpose({
  acceptParams
});
</script>
<style scoped lang="scss">
.address-box {
  display: flex;
}

.file-upload-box {
  display: flex;
  width: 100%;
  // border: 1px solid red;
}

.work-wrapper {
  display: flex;
  flex-direction: column;
  width: 100%;

  .btn-wrapper {
    height: 30px;
    // border: 1px solid red;
  }
  .item-wrapper {
    margin: 5px 0;
    // border: 1px solid green;

    .item-mid {
      margin: 0 5px;
    }
  }
}

.address-wrapper {
  width: 100%;
  // border: 1px solid red;
  display: flex;
  align-items: center;

  .address-input {
    flex: 1;
  }

  .address-btn {
    width: 20%;
  }
}

.custom-wrapper {
  border: 1px solid var(--el-color-info-light-7);
  width: 100%;
  height: 40px;
  line-height: 40px;
  border-radius: 4px;

  .mx-1 {
    margin: 0 5px;
  }

  .w-20 {
    width: 200px;
  }
}
</style>
